#include "OptionsModule.h"
#include "ClientAppDialogSet.h"

#include "rutil/DnsUtil.hxx"
#include "resip/dum/MasterProfile.hxx"

#include <iostream>

using namespace resip;
using namespace std;

OptionsModule::OptionsModule(DialogUsageManager* dum, SipStack* stack) : m_optionsHandler(0), m_dialogUsageManager(dum), m_stack(stack)
{
	initialize();
}

OptionsModule::~OptionsModule()
{
	cleanup();
}

void OptionsModule::initialize()
{
	// Initialize OptionsHandler

	initializeHandler();

	// Initialize Users

	initializeUsers();
}

void OptionsModule::cleanup()
{
	if( m_optionsHandler )
	{
		delete m_optionsHandler;
		m_optionsHandler = 0;
	}
}

void OptionsModule::waitForResponse()
{
	while( !m_optionsHandler->isDone() )
	{
		FdSet fdset;
		m_stack->buildFdSet(fdset);
		fdset.selectMilliSeconds(SELECT_TIME);
		m_stack->process(fdset);

		while( m_dialogUsageManager->process() )
			;
	}
}

void OptionsModule::setScheme(string scheme)
{
	m_baseAor.uri().scheme() = scheme.c_str();
	m_destAor.uri().scheme() = scheme.c_str();
}

void OptionsModule::setBaseUser(string user)
{
	m_baseAor.uri().user() = user.c_str();
}

void OptionsModule::setDestUser(string user)
{
	m_destAor.uri().user() = user.c_str();
}

void OptionsModule::setDestHost(string uri)
{
	m_destAor.uri().host() = uri.c_str();
}

void OptionsModule::setDestPassword(string password)
{
	m_password = password;
}

void OptionsModule::sendOptionsMessage()
{
	// Do necessairy configuration

	m_dialogUsageManager->getMasterProfile()->setDefaultFrom(m_baseAor);
	m_dialogUsageManager->getMasterProfile()-> setDigestCredential(m_destAor.uri().host(),
		m_destAor.uri().user(), Data(m_password) );

	// Make OPTIONS message

	SharedPtr<SipMessage> request = m_dialogUsageManager->makeOutOfDialogRequest(m_destAor, OPTIONS, new ClientAppDialogSet(*m_dialogUsageManager));
	m_dialogUsageManager->send(request);

	// Wait for response

	waitForResponse();
}

void OptionsModule::initializeHandler()
{
	m_optionsHandler = new OptionsHandler();
	m_dialogUsageManager->addOutOfDialogHandler(OPTIONS, m_optionsHandler);
}

void OptionsModule::initializeUsers()
{
	m_baseAor.uri().port() = BASEPORT;
	m_baseAor.uri().host() = DnsUtil::getLocalIpAddress();

	m_destAor.uri().port() = DESTPORT;
}